using UnityEngine;
using UnityEditor;
using System.Text;
using EntityKit.Runtime;
using System;

namespace EntityKit.Editor
{
    public static class EntityComponentSubLocation
    {
        public static void CopyEntityComponentPathToClipboard()
        {
            if (Selection.activeGameObject == null)
            {
                Debug.LogWarning("请先选择一个GameObject");
                return;
            }

            string path = GetEntityComponentPath(Selection.activeGameObject.transform);
            EditorGUIUtility.systemCopyBuffer = path;
            Debug.Log($"已复制路径到剪贴板: {path}");
        }

        /// <summary>
        /// 获取从根到指定Transform的路径
        /// </summary>
        /// <param name="target">目标Transform</param>
        /// <returns>UI路径</returns>
        private static string GetEntityComponentPath(Transform target)
        {
            if (target == null) return string.Empty;

            StringBuilder path = new StringBuilder();
            Transform current = target;

            // 向上遍历直到根节点或EntityComponent
            while (current != null && !HasEntityComponent(current))
            {
                if (path.Length > 0)
                    path.Insert(0, "/");
                
                path.Insert(0, current.name);
                current = current.parent;
            }

            return path.ToString();
        }
        
        /// <summary>
        /// 检查Transform上是否有EntityComponent组件（支持泛型类型）
        /// </summary>
        /// <param name="transform">要检查的Transform</param>
        /// <returns>是否有EntityComponent组件</returns>
        static bool HasEntityComponent(Transform transform)
        {
            // 获取所有组件
            Component[] components = transform.GetComponents<Component>();
            
            // 检查每个组件是否继承自EntityComponent<>
            foreach (Component component in components)
            {
                if (component == null) continue;
                
                Type componentType = component.GetType();
                
                // 检查是否是EntityComponent的子类
                while (componentType != null && componentType != typeof(object))
                {
                    if (componentType.IsGenericType && componentType.GetGenericTypeDefinition() == typeof(EntityComponent<>))
                    {
                        return true;
                    }
                    componentType = componentType.BaseType;
                }
            }
            
            return false;
        }
    }
}